package my.avoskagae.store.virtual;

import java.util.ArrayList;
import java.util.List;

import com.google.inject.Singleton;

import my.avoskagae.model.entity.Product;
import my.avoskagae.store.abstr.StoreAdapter;
import my.avoskagae.store.virtual.entity.ProductImpl;

@Singleton
public class VirtualStoreAdapterImpl implements StoreAdapter {

	private final List<Product> products = new ArrayList<Product>();

	@Override
	public List<Product> getProducts() {
		return (List<Product>)products;
	}
	
	@Override
	public Product findPrductByName(String name) {
		for (Product p: products){
			if (p.getName().equals(name)) 
				{return p;}
		}
		return null;
	}

	@Override
	public Product createProduct(String name){
		ProductImpl p = new ProductImpl(name);
		p.setId(ProductImpl.getCounter());
		products.add(p);
		return p;
	}
	
	@Override
	public boolean removeProduct(Product product) {
		return products.remove(findById(product));
	}

	@Override
	public boolean updateProduct(Product product) {
		Product p = findById(product);
		if (p!=null) {
			p.setName(product.getName());
			return true;
		} else {
			return false;
		}
	}

	
	private Product findById(Product product){
		int id = ((ProductImpl)product).getId();
		for (Product p: products){
			//TODO Избавится от приведения типов
			if (((ProductImpl)p).getId()==id) 
				{return p;}
		}
		return null;
	}

}
